package com.wolfking.jeesite.exception;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.concurrent.TimeoutException;


/**
 * RESTful服务返回的错误信息
 * <p>
 *
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月18日下午2:46:48
 * @版权 归wolfking所有
 */
public class JeesiteException extends RuntimeException implements Serializable {
    private static final Logger logger = LoggerFactory.getLogger(JeesiteException.class);
    private static final long serialVersionUID = 2640926329092743174L;
    // 统一错误码
    private int code;
    // 错误信息摘要
    private String message;
    // 错误信息详情（主要用于调试）
    private String detail = "";

    public JeesiteException() {
    }

    public JeesiteException(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public JeesiteException(int code, String message, String detail) {
        this.code = code;
        this.message = message;
        this.detail = detail;
    }

    public JeesiteException(ExceptionCode errorCode) {
        this.code = errorCode.value();
        this.message = errorCode.msg();
    }

    public JeesiteException(ExceptionCode errorCode, String detail) {
        this.code = errorCode.value();
        this.message = errorCode.msg();
        this.detail = detail;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public static JeesiteException parse(Exception e) {
        if (e instanceof JeesiteException) {
            return (JeesiteException) e;
        }
        String err = e.getMessage();
        try {
            if (e instanceof TimeoutException) {
                return new JeesiteException(ExceptionCode.SYS_ERROR_RPC_CONNECTION, "远程服务调用超时");
            } else if (err.indexOf("content:") < 0) {
                logger.debug("其他错误", e);
                return new JeesiteException(ExceptionCode.BIZ_ERROR.value(), e.getMessage());
            } else {
                return new Gson().fromJson(err.split("content:")[1], JeesiteException.class);
            }
        } catch (Exception e1) {
            logger.error("从异常信息中解析ErrorMsg失败", e1);
            return new JeesiteException(ExceptionCode.SYS_ERROR, err);
        }
    }
}
